package com.mj.mes.system.SysResource;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mj.mes.utils.BaseBeanDao;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mj on 2017/3/30.
 */
@RestController
@RequestMapping("resource")
public class SysResourceController {
    @Autowired
    private SysResourceService sysResourceService;

    @Autowired
    private BaseBeanDao baseBeanDao;

    /**
     * 资源菜单
     *
     * @return
     */
    @RequestMapping("queryAll")
    @ResponseBody
    public Map<String, Object> findAll() throws JSONException, JsonProcessingException {
        Map listMap = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        List<SysResource> list = sysResourceService.findAll();
        List arrayList = new ArrayList();
        for (SysResource sysResource : list) {
            Object object = sysResource;
            if (sysResource.getSysResource() != null) {
                object = baseBeanDao.addAttributes(sysResource, "_parentId", sysResource.getSysResource().getId());
            }
            arrayList.add(object);
        }
        listMap.put("rows", arrayList);
        return listMap;
    }

    @RequestMapping("addResource")
    public Map<String, Object> addResource(SysResource sysResource, String parentId) {
        Map<String, Object> map = new HashedMap();
        if (!StringUtils.isEmpty(parentId)) {
            SysResource parentSysResource = sysResourceService.findOne(Long.valueOf(parentId));
            sysResource.setSysResource(parentSysResource);
        }

        try {
            sysResourceService.save(sysResource);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }

    @RequestMapping("removeResource")
    public Map<String, Object> removeResource(SysResource sysResource) {
        Map<String, Object> map = new HashedMap();
        try {
            sysResource = sysResourceService.findOne(Long.valueOf(sysResource.getId()));
            sysResourceService.remove(sysResource);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }
}
